import tkinter as tk
import random
import time

class SnakeGame:
    def __init__(self, master):
        self.master = master
        self.master.title("贪吃蛇")
        self.master.resizable(False, False)
        
        # 游戏设置
        self.width = 600
        self.height = 600
        self.grid_size = 20
        self.speed = 150  # 初始速度(毫秒)
        
        # 游戏状态
        self.snake = [(100, 100), (80, 100), (60, 100)]
        self.direction = "Right"
        self.next_direction = "Right"
        self.food = self.create_food()
        self.score = 0
        self.game_over = False
        
        # 创建UI
        self.create_ui()
        
        # 绑定键盘事件
        self.master.bind("<Key>", self.on_key_press)
        
        # 开始游戏
        self.start_game()
    
    def create_ui(self):
        # 创建画布
        self.canvas = tk.Canvas(
            self.master, 
            width=self.width, 
            height=self.height, 
            bg="black",
            highlightthickness=0
        )
        self.canvas.pack()
        
        # 创建分数显示
        self.score_label = self.canvas.create_text(
            self.width // 2, 
            20, 
            text=f"分数: {self.score}", 
            fill="white", 
            font=("Arial", 16, "bold")
        )
    
    def create_food(self):
        """在随机位置创建食物"""
        while True:
            x = random.randint(1, (self.width - self.grid_size) // self.grid_size) * self.grid_size
            y = random.randint(1, (self.height - self.grid_size) // self.grid_size) * self.grid_size
            
            # 确保食物不会出现在蛇身上
            if (x, y) not in self.snake:
                return (x, y)
    
    def update_score(self):
        """更新分数显示"""
        self.canvas.itemconfig(self.score_label, text=f"分数: {self.score}")
    
    def move_snake(self):
        """移动蛇"""
        if self.game_over:
            return
        
        # 更新方向
        self.direction = self.next_direction
        
        # 获取蛇头位置
        head_x, head_y = self.snake[0]
        
        # 根据方向移动蛇头
        if self.direction == "Up":
            head_y -= self.grid_size
        elif self.direction == "Down":
            head_y += self.grid_size
        elif self.direction == "Left":
            head_x -= self.grid_size
        elif self.direction == "Right":
            head_x += self.grid_size
        
        # 检查是否撞墙
        if (
            head_x < 0 
            or head_x >= self.width 
            or head_y < 0 
            or head_y >= self.height
        ):
            self.game_over = True
            self.show_game_over()
            return
        
        # 检查是否撞到自己
        if (head_x, head_y) in self.snake:
            self.game_over = True
            self.show_game_over()
            return
        
        # 将新的蛇头添加到蛇身
        self.snake.insert(0, (head_x, head_y))
        
        # 检查是否吃到食物
        if self.snake[0] == self.food:
            self.score += 10
            self.update_score()
            self.food = self.create_food()
            
            # 增加游戏难度
            if self.score % 50 == 0 and self.speed > 50:
                self.speed -= 10
        else:
            # 如果没吃到食物，移除尾部
            self.snake.pop()
    
    def draw(self):
        """绘制游戏元素"""
        self.canvas.delete("all")
        
        # 绘制分数
        self.canvas.create_text(
            self.width // 2, 
            20, 
            text=f"分数: {self.score}", 
            fill="white", 
            font=("Arial", 16, "bold")
        )
        
        # 绘制蛇
        for segment in self.snake:
            x, y = segment
            self.canvas.create_rectangle(
                x, y, 
                x + self.grid_size, 
                y + self.grid_size,
                fill="green", 
                outline="black"
            )
        
        # 绘制蛇头
        head_x, head_y = self.snake[0]
        self.canvas.create_rectangle(
            head_x, head_y, 
            head_x + self.grid_size, 
            head_y + self.grid_size,
            fill="darkgreen", 
            outline="black"
        )
        
        # 绘制食物
        food_x, food_y = self.food
        self.canvas.create_oval(
            food_x, food_y, 
            food_x + self.grid_size, 
            food_y + self.grid_size,
            fill="red", 
            outline="black"
        )
        
        # 如果游戏结束，显示游戏结束信息
        if self.game_over:
            self.show_game_over()
    
    def show_game_over(self):
        """显示游戏结束信息"""
        self.canvas.create_rectangle(
            self.width // 4, 
            self.height // 3, 
            self.width * 3 // 4, 
            self.height * 2 // 3,
            fill="black", 
            outline="white"
        )
        
        self.canvas.create_text(
            self.width // 2, 
            self.height // 2 - 30, 
            text="游戏结束", 
            fill="white", 
            font=("Arial", 24, "bold")
        )
        
        self.canvas.create_text(
            self.width // 2, 
            self.height // 2 + 10, 
            text=f"最终分数: {self.score}", 
            fill="white", 
            font=("Arial", 16)
        )
        
        self.canvas.create_text(
            self.width // 2, 
            self.height // 2 + 50, 
            text="按空格键重新开始", 
            fill="white", 
            font=("Arial", 12)
        )
    
    def on_key_press(self, event):
        """处理键盘事件"""
        key = event.keysym
        
        if (key == "Up" and self.direction != "Down") or \
           (key == "Down" and self.direction != "Up") or \
           (key == "Left" and self.direction != "Right") or \
           (key == "Right" and self.direction != "Left"):
            self.next_direction = key
        
        # 按空格键重新开始游戏
        if key == "space" and self.game_over:
            self.reset_game()
    
    def reset_game(self):
        """重置游戏"""
        self.snake = [(100, 100), (80, 100), (60, 100)]
        self.direction = "Right"
        self.next_direction = "Right"
        self.food = self.create_food()
        self.score = 0
        self.game_over = False
        self.speed = 150
        self.update_score()
        self.draw()
    
    def start_game(self):
        """开始游戏循环"""
        self.draw()
        self.game_loop()
    
    def game_loop(self):
        """游戏主循环"""
        if not self.game_over:
            self.move_snake()
            self.draw()
            self.master.after(self.speed, self.game_loop)

if __name__ == "__main__":
    root = tk.Tk()
    game = SnakeGame(root)
    root.mainloop()